import { Pressable, StyleSheet, View, ImageBackground, Animated, Easing, Text } from 'react-native';
import React, { useRef, useEffect, useState } from 'react';
import { useNavigation, useFocusEffect, useRoute } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import { Camera, useCodeScanner, useCameraDevice } from 'react-native-vision-camera';
import { checkAndRequestLocationPermissions, checkAndRequestBluetoothPermissions } from '~/utils/permission';
import { useTranslation } from 'react-i18next';
import { FocusAwareStatusBar } from '~/components';
import { px2dp, width, scale } from '~/utils/px2dp';
import { observer, deviceStore } from '~/store';

export default observer(() => {
    const { t } = useTranslation();
    const router: any = useRoute();
    // 五穴同频使用
    const {
        routePage = '',
        body_index = '',
        course_id = '',
        titleId = '',
        actionType,
        id,
        write_id,
        oldDeviceSn,
    } = router.params || {};
    const [isCameraActive, setIsCameraActive] = useState(true);
    const navigation: any = useNavigation();
    const device: any = useCameraDevice('back');
    const moveAnim = useRef(new Animated.Value(-2)).current;
    useFocusEffect(
        React.useCallback(() => {
            setIsCameraActive(true);
            return () => {
                setIsCameraActive(false);
            };
        }, []),
    );

    const startAnimation = () => {
        Animated.sequence([
            Animated.timing(moveAnim, {
                toValue: 200,
                duration: 1500,
                easing: Easing.linear,
                useNativeDriver: false,
            }),
            Animated.timing(moveAnim, {
                toValue: -1,
                duration: 1500,
                easing: Easing.linear,
                useNativeDriver: false,
            }),
        ]).start(() => startAnimation());
    };
    const codeScanner = useCodeScanner({
        codeTypes: ['qr', 'ean-13'],
        onCodeScanned: (codes) => {
            if (codes.length > 0) {
                const device_sn = codes[0].value;
                if (routePage == 'Acupoints') {
                    const searchDevices = deviceStore.device.searchDevices || [];
                    const matchedDevice = searchDevices.find((device) => device.device_sn == device_sn) || {
                        device_sn: '',
                        id: '',
                    };
                    if (matchedDevice?.device_sn) {
                        navigation.navigate('ScanDeviceResult', {
                            device_sn,
                            body_index,
                            course_id,
                            titleId,
                            actionType,
                            id,
                            write_id,
                            oldDeviceSn,
                            routePage,
                        });
                    } else {
                        navigation.goBack();
                        Toast.show({ content: t('ScanBleDevice.t4') });
                    }
                } else {
                    navigation.navigate('ScanDeviceResult', { device_sn });
                }
            }
        },
    });

    useEffect(() => {
        startAnimation();
    }, []);

    // 蓝牙连接设备
    const addBleDevice = async () => {
        const hasLocationPermissions = await checkAndRequestLocationPermissions();
        const hasBluetoothPermissions = await checkAndRequestBluetoothPermissions();
        if (!hasLocationPermissions && hasBluetoothPermissions) {
            Toast.show({ content: t('ScanBleDevice.t2'), layout: 'top' });
            return;
        }
        if (deviceStore.device.deviceStatus == 0) {
            Toast.show({ content: t('ScanBleDevice.t3'), layout: 'top' });
            return;
        }
        navigation.navigate('SearchBleDevice', {
            body_index,
            course_id,
            titleId,
            actionType,
            id,
            write_id,
            oldDeviceSn,
            routePage,
        });
    };

    return (
        <View style={styles.container}>
            <FocusAwareStatusBar translucent={true} />
            <View style={[styles.navBar, styles.row]}>
                <Pressable onPress={() => navigation.goBack()}>
                    <Icon name="chevron-back-outline" size={30} color={'#000'}></Icon>
                </Pressable>
                <Text></Text>
                <Pressable onPress={addBleDevice} style={styles.bleSearchDevice}>
                    <Text style={styles.title}>{t('ScanBleDevice.t1')}</Text>
                </Pressable>
            </View>
            <Camera
                isActive={isCameraActive}
                style={StyleSheet.absoluteFill}
                device={device}
                codeScanner={codeScanner}
            />
            <View style={styles.scanContainer}>
                <ImageBackground source={require('~/assets/user/qr.png')} style={[styles.icons]}>
                    <Animated.View style={[styles.border, { transform: [{ translateY: moveAnim }] }]} />
                </ImageBackground>
            </View>
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    container: {
        flex: 1,
    },
    navBar: {
        position: 'absolute',
        width: width - px2dp(64),
        marginHorizontal: px2dp(32),
        top: '6%',
        zIndex: 99999,
        justifyContent: 'space-between',
    },
    absoluteFill: {
        width: px2dp(300),
        height: px2dp(300),
        backgroundColor: 'red',
    },
    scanContainer: {
        justifyContent: 'center',
        alignItems: 'center',
        flexGrow: 1,
    },
    icons: {
        width: px2dp(400),
        height: px2dp(400),
    },
    border: {
        width: px2dp(400),
        height: px2dp(4),
        backgroundColor: '#fff',
    },
    bleSearchDevice: {
        paddingHorizontal: px2dp(24),
        paddingVertical: px2dp(12),
        backgroundColor: '#3B71FE',
        borderRadius: px2dp(999),
    },
    title: {
        color: '#fff',
        fontWeight: 'bold',
        fontSize: scale(30),
    },
});
